{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !wget https://storage.googleapis.com/bert_models/2018_11_23/multi_cased_L-12_H-768_A-12.zip\n",
    "# !unzip multi_cased_L-12_H-768_A-12.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:87: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import bert\n",
    "from bert import run_classifier\n",
    "from bert import optimization\n",
    "from bert import tokenization\n",
    "from bert import modeling\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import pandas as pd\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "with open('dataset.json') as fopen:\n",
    "    data = json.load(fopen)\n",
    "    \n",
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/tokenization.py:125: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "BERT_VOCAB = 'multi_cased_L-12_H-768_A-12/vocab.txt'\n",
    "BERT_INIT_CHKPNT = 'multi_cased_L-12_H-768_A-12/bert_model.ckpt'\n",
    "BERT_CONFIG = 'multi_cased_L-12_H-768_A-12/bert_config.json'\n",
    "\n",
    "tokenizer = tokenization.FullTokenizer(\n",
    "      vocab_file=BERT_VOCAB, do_lower_case=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "GO = 101\n",
    "EOS = 102"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from unidecode import unidecode\n",
    "\n",
    "def get_inputs(x, y):\n",
    "    input_ids, input_masks, segment_ids, ys = [], [], [], []\n",
    "    for i in tqdm(range(len(x))):\n",
    "        tokens_a = tokenizer.tokenize(unidecode(x[i]))\n",
    "        tokens_b = tokenizer.tokenize(unidecode(y[i]))\n",
    "        tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n",
    "        \n",
    "        segment_id = [0] * len(tokens)\n",
    "        input_id = tokenizer.convert_tokens_to_ids(tokens)\n",
    "        input_mask = [1] * len(input_id)\n",
    "\n",
    "        input_ids.append(input_id)\n",
    "        input_masks.append(input_mask)\n",
    "        segment_ids.append(segment_id)\n",
    "        \n",
    "        r = tokenizer.convert_tokens_to_ids(tokens_b + [\"[SEP]\"])\n",
    "        if len([k for k in r if k == 0]):\n",
    "            print(y[i], i)\n",
    "            break\n",
    "        \n",
    "        ys.append(r)\n",
    "        \n",
    "    return input_ids, input_masks, segment_ids, ys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 200000/200000 [02:25<00:00, 1372.95it/s]\n"
     ]
    }
   ],
   "source": [
    "train_input_ids, train_input_masks, train_segment_ids, train_Y = get_inputs(train_X, train_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5000/5000 [00:03<00:00, 1448.79it/s]\n"
     ]
    }
   ],
   "source": [
    "test_input_ids, test_input_masks, test_segment_ids, test_Y = get_inputs(test_X, test_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "bert_config = modeling.BertConfig.from_json_file(BERT_CONFIG)\n",
    "epoch = 20\n",
    "batch_size = 16\n",
    "warmup_proportion = 0.1\n",
    "num_train_steps = len(train_input_ids)\n",
    "num_warmup_steps = int(num_train_steps * warmup_proportion)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "import bert_decoder as modeling_decoder\n",
    "\n",
    "class Model:\n",
    "    def __init__(\n",
    "        self,\n",
    "        learning_rate = 2e-5,\n",
    "        training = True,\n",
    "    ):\n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.segment_ids = tf.placeholder(tf.int32, [None, None])\n",
    "        self.input_masks = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        def forward(x, segment, masks, y, reuse = False, config = bert_config):\n",
    "            \n",
    "            with tf.variable_scope('bert',reuse=reuse):\n",
    "        \n",
    "                model = modeling.BertModel(\n",
    "                    config=config,\n",
    "                    is_training=training,\n",
    "                    input_ids=x,\n",
    "                    input_mask=masks,\n",
    "                    token_type_ids=segment,\n",
    "                    use_one_hot_embeddings=False)\n",
    "                memory = model.get_sequence_output()\n",
    "            \n",
    "            with tf.variable_scope('bert',reuse=True):\n",
    "                Y_seq_len = tf.count_nonzero(y, 1, dtype=tf.int32)\n",
    "                y_masks = tf.sequence_mask(Y_seq_len, tf.reduce_max(Y_seq_len), dtype=tf.float32)\n",
    "                \n",
    "                model = modeling_decoder.BertModel(\n",
    "                    config=config,\n",
    "                    is_training=training,\n",
    "                    input_ids=y,\n",
    "                    input_mask=y_masks,\n",
    "                    memory = memory,\n",
    "                    memory_mask = masks,\n",
    "                    use_one_hot_embeddings=False)\n",
    "                output_layer = model.get_sequence_output()\n",
    "                embedding = model.get_embedding_table()\n",
    "                \n",
    "            with tf.variable_scope('cls/predictions',reuse=reuse):\n",
    "                with tf.variable_scope('transform'):\n",
    "                    input_tensor = tf.layers.dense(\n",
    "                    output_layer,\n",
    "                    units = config.hidden_size,\n",
    "                    activation = modeling.get_activation(bert_config.hidden_act),\n",
    "                    kernel_initializer = modeling.create_initializer(\n",
    "                        bert_config.initializer_range\n",
    "                    ),\n",
    "                )\n",
    "                input_tensor = modeling.layer_norm(input_tensor)\n",
    "\n",
    "                output_bias = tf.get_variable(\n",
    "                'output_bias',\n",
    "                shape = [bert_config.vocab_size],\n",
    "                initializer = tf.zeros_initializer(),\n",
    "                )\n",
    "                logits = tf.matmul(input_tensor, embedding, transpose_b = True)\n",
    "                return logits\n",
    "\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        \n",
    "        self.training_logits = forward(self.X, self.segment_ids, self.input_masks, decoder_input)\n",
    "        print(self.training_logits)\n",
    "\n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        \n",
    "        self.optimizer = optimization.create_optimizer(self.cost, learning_rate, \n",
    "                                                       num_train_steps, num_warmup_steps, False)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        \n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            segment = tf.contrib.seq2seq.tile_batch(self.segment_ids, 1)\n",
    "            masks = tf.contrib.seq2seq.tile_batch(self.input_masks, 1)\n",
    "            logits = forward(x, segment, masks, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            bert_config.vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids\n",
    "        self.fast_result = tf.identity(self.fast_result, name = 'greedy')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:409: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:490: The name tf.assert_less_equal is deprecated. Please use tf.compat.v1.assert_less_equal instead.\n",
      "\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:358: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:671: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "Tensor(\"cls/predictions/MatMul:0\", shape=(?, ?, 119547), dtype=float32)\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:27: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:32: The name tf.train.polynomial_decay is deprecated. Please use tf.compat.v1.train.polynomial_decay instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:70: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/math_grad.py:1375: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model()\n",
    "\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import re\n",
    "\n",
    "def get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n",
    "    \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n",
    "    assignment_map = {}\n",
    "    initialized_variable_names = {}\n",
    "\n",
    "    name_to_variable = collections.OrderedDict()\n",
    "    for var in tvars:\n",
    "        name = var.name\n",
    "        m = re.match('^(.*):\\\\d+$', name)\n",
    "        if m is not None:\n",
    "            name = m.group(1)\n",
    "        name_to_variable[name] = var\n",
    "\n",
    "    init_vars = tf.train.list_variables(init_checkpoint)\n",
    "\n",
    "    assignment_map = collections.OrderedDict()\n",
    "    for x in init_vars:\n",
    "        (name, var) = (x[0], x[1])\n",
    "        if 'bert/' + name in name_to_variable:\n",
    "            assignment_map[name] = name_to_variable['bert/' + name]\n",
    "            initialized_variable_names[name] = 1\n",
    "            initialized_variable_names[name + ':0'] = 1\n",
    "        elif name in name_to_variable:\n",
    "            assignment_map[name] = name_to_variable[name]\n",
    "            initialized_variable_names[name] = 1\n",
    "            initialized_variable_names[name + ':0'] = 1\n",
    "        \n",
    "\n",
    "    return (assignment_map, initialized_variable_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "tvars = tf.trainable_variables()\n",
    "\n",
    "checkpoint = BERT_INIT_CHKPNT\n",
    "assignment_map, initialized_variable_names = get_assignment_map_from_checkpoint(tvars, \n",
    "                                                                                checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from multi_cased_L-12_H-768_A-12/bert_model.ckpt\n"
     ]
    }
   ],
   "source": [
    "saver = tf.train.Saver(var_list = assignment_map)\n",
    "saver.restore(sess, checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:58<00:00,  2.89it/s, accuracy=0.508, cost=2.58]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  7.83it/s, accuracy=0.604, cost=1.99]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, training loss: 3.531583, training acc: 0.397134, valid loss: 2.287189, valid acc: 0.551373\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:56<00:00,  2.90it/s, accuracy=0.606, cost=2.06]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  7.98it/s, accuracy=0.682, cost=1.62]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 1, training loss: 2.028329, training acc: 0.590376, valid loss: 1.858868, valid acc: 0.615519\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:51<00:00,  2.90it/s, accuracy=0.636, cost=1.81]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.00it/s, accuracy=0.698, cost=1.5] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 2, training loss: 1.729738, training acc: 0.635133, valid loss: 1.720596, valid acc: 0.637721\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:24<00:00,  2.92it/s, accuracy=0.657, cost=1.67] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.01it/s, accuracy=0.714, cost=1.43]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 3, training loss: 1.578060, training acc: 0.658273, valid loss: 1.655395, valid acc: 0.647892\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:08<00:00,  2.93it/s, accuracy=0.667, cost=1.58] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.698, cost=1.39]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 4, training loss: 1.473376, training acc: 0.674592, valid loss: 1.618933, valid acc: 0.653053\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:06<00:00,  2.93it/s, accuracy=0.672, cost=1.54] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.702, cost=1.4] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 5, training loss: 1.391641, training acc: 0.687722, valid loss: 1.599395, valid acc: 0.655963\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:03<00:00,  2.93it/s, accuracy=0.689, cost=1.46] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.706, cost=1.43]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 6, training loss: 1.324112, training acc: 0.698737, valid loss: 1.589253, valid acc: 0.657487\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:  22%|██▏       | 2748/12500 [15:36<52:59,  3.07it/s, accuracy=0.7, cost=1.28]     IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  54%|█████▍    | 6762/12500 [38:24<33:35,  2.85it/s, accuracy=0.655, cost=1.53] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop:  85%|████████▌ | 10656/12500 [1:00:30<10:35,  2.90it/s, accuracy=0.647, cost=1.55] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.727, cost=1.37] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 7, training loss: 1.265991, training acc: 0.708689, valid loss: 1.586499, valid acc: 0.659481\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:  11%|█         | 1336/12500 [07:35<1:03:03,  2.95it/s, accuracy=0.652, cost=1.52] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:00<00:00,  2.93it/s, accuracy=0.701, cost=1.39] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.01it/s, accuracy=0.735, cost=1.39] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 8, training loss: 1.216411, training acc: 0.716923, valid loss: 1.583633, valid acc: 0.660710\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:07<00:00,  2.93it/s, accuracy=0.701, cost=1.25] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.702, cost=1.42] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 9, training loss: 1.172203, training acc: 0.724828, valid loss: 1.578793, valid acc: 0.661640\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:05<00:00,  2.93it/s, accuracy=0.727, cost=1.23] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.702, cost=1.46] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 10, training loss: 1.134783, training acc: 0.731420, valid loss: 1.586898, valid acc: 0.659380\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:22<00:00,  2.92it/s, accuracy=0.722, cost=1.21] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.706, cost=1.36]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 11, training loss: 1.101593, training acc: 0.737372, valid loss: 1.594484, valid acc: 0.660313\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:10<00:00,  2.93it/s, accuracy=0.761, cost=1.12] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.01it/s, accuracy=0.714, cost=1.45] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 12, training loss: 1.073733, training acc: 0.742576, valid loss: 1.591513, valid acc: 0.662239\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:13:23<00:00,  2.84it/s, accuracy=0.746, cost=1.12] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.01it/s, accuracy=0.731, cost=1.3] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 13, training loss: 1.050413, training acc: 0.746995, valid loss: 1.593687, valid acc: 0.662296\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:11<00:00,  2.93it/s, accuracy=0.746, cost=1.12] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.00it/s, accuracy=0.718, cost=1.37] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 14, training loss: 1.032093, training acc: 0.750512, valid loss: 1.597060, valid acc: 0.662915\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:08<00:00,  2.93it/s, accuracy=0.744, cost=1.13] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.01it/s, accuracy=0.743, cost=1.35] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 15, training loss: 1.018339, training acc: 0.753089, valid loss: 1.596794, valid acc: 0.662569\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:04<00:00,  2.93it/s, accuracy=0.739, cost=1.12] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.01it/s, accuracy=0.731, cost=1.41] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 16, training loss: 1.011239, training acc: 0.754462, valid loss: 1.596209, valid acc: 0.662928\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:03<00:00,  2.93it/s, accuracy=0.739, cost=1.08] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.731, cost=1.36] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 17, training loss: 1.011306, training acc: 0.754584, valid loss: 1.594291, valid acc: 0.661916\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop:  71%|███████▏  | 8918/12500 [50:40<20:47,  2.87it/s, accuracy=0.752, cost=1.04]   IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:04<00:00,  2.93it/s, accuracy=0.744, cost=1.11] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:38<00:00,  8.03it/s, accuracy=0.718, cost=1.39] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 18, training loss: 1.011215, training acc: 0.754533, valid loss: 1.592084, valid acc: 0.662477\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:11:03<00:00,  2.93it/s, accuracy=0.737, cost=1.11] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:39<00:00,  8.02it/s, accuracy=0.735, cost=1.49] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 19, training loss: 1.011770, training acc: 0.754386, valid loss: 1.596818, valid acc: 0.661871\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "import time\n",
    "\n",
    "for EPOCH in range(epoch):\n",
    "\n",
    "    train_acc, train_loss, test_acc, test_loss = [], [], [], []\n",
    "    pbar = tqdm(\n",
    "        range(0, len(train_input_ids), batch_size), desc = 'train minibatch loop'\n",
    "    )\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_input_ids))\n",
    "        batch_x = train_input_ids[i: index]\n",
    "        batch_x = pad_sequences(batch_x, padding='post')\n",
    "        batch_mask = train_input_masks[i: index]\n",
    "        batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "        batch_segment = train_segment_ids[i: index]\n",
    "        batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i: index], padding='post')\n",
    "        acc, cost, _ = sess.run(\n",
    "            [model.accuracy, model.cost, model.optimizer],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.input_masks: batch_mask,\n",
    "                model.segment_ids: batch_segment\n",
    "            },\n",
    "        )\n",
    "        train_loss.append(cost)\n",
    "        train_acc.append(acc)\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "        \n",
    "    pbar = tqdm(range(0, len(test_input_ids), batch_size), desc = 'test minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_input_ids))\n",
    "        batch_x = test_input_ids[i: index]\n",
    "        batch_x = pad_sequences(batch_x, padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i: index], padding='post')\n",
    "        batch_mask = test_input_masks[i: index]\n",
    "        batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "        batch_segment = test_segment_ids[i: index]\n",
    "        batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "        acc, cost = sess.run(\n",
    "            [model.accuracy, model.cost],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.input_masks: batch_mask,\n",
    "                model.segment_ids: batch_segment\n",
    "            },\n",
    "        )\n",
    "        test_loss.append(cost)\n",
    "        test_acc.append(acc)\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "        \n",
    "    train_loss = np.mean(train_loss)\n",
    "    train_acc = np.mean(train_acc)\n",
    "    test_loss = np.mean(test_loss)\n",
    "    test_acc = np.mean(test_acc)\n",
    "    print(\n",
    "        'epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'\n",
    "        % (EPOCH, train_loss, train_acc, test_loss, test_acc)\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 313/313 [15:48<00:00,  3.03s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = test_input_ids[i: index]\n",
    "    batch_x = pad_sequences(batch_x, padding='post')\n",
    "    batch_y = pad_sequences(test_Y[i: index], padding='post')\n",
    "    batch_mask = test_input_masks[i: index]\n",
    "    batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "    batch_segment = test_segment_ids[i: index]\n",
    "    batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "    feed = {\n",
    "        model.X: batch_x,\n",
    "        model.input_masks: batch_mask,\n",
    "        model.segment_ids: batch_segment\n",
    "    }\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3 and i not in [101, 102]])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3 and i not in [101, 102]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.37003958"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
